package com.laikan.reader.bookfriend.activity;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.View;
import android.widget.*;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.adapter.Personal_Consume_Adapter;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BaseListDataBean;
import com.laikan.reader.core.bean.Consume;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.view.ProgressBar_Modern;
import com.laikan.reader.core.view.TouchSwipeRefreshLayout;
import com.socks.library.KLog;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static com.laikan.library.managers.ToastMgr.showShortToast;

/**
 * @author wx
 * @category 个人消费信息页面，个人中心的二级页面
 */
@SuppressLint ("HandlerLeak")
public class PersonalConsume extends BasicActivity {

    private ArrayList<Consume> mData = new ArrayList<Consume>();// 接受数据的容器
    private ListView mListView;
    private Personal_Consume_Adapter mAdapter;
    private int mCurrentPage = 1;
    private int total;// 返回的数据总数
    private boolean isDown = true;// 是否下拉
    //    private PercentLinearLayout no_consume;
    private LinearLayout no_consume;
    private ImageView back_tv;
    Drawable drawable_back_tv;
    private RelativeLayout back_layout;
    private ProgressBar_Modern mProgressBar_Modern;
    private TouchSwipeRefreshLayout mCommentSwipeRefresh;
    private View listview_footer;
    private long mLoadNoreInternalTime;

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void assignViews() {
        setContentView(R.layout.personal_consume);
        no_consume = (LinearLayout)findViewById(R.id.no_consume);
        mListView = (ListView)findViewById(R.id.listview_personals);
        mAdapter = new Personal_Consume_Adapter(mContext, mData);
        mProgressBar_Modern = (ProgressBar_Modern)findViewById(R.id.progressbar_modern);
        mListView.setAdapter(mAdapter);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        mCommentSwipeRefresh = (TouchSwipeRefreshLayout)findViewById(R.id.common_swiperefresh);
        mCommentSwipeRefresh.setColorSchemeResources(R.color.C_66ccdd);
        mCommentSwipeRefresh.setEnabled(false);
        listview_footer = View.inflate(mContext, R.layout.search_new_foot_view, null);
        listview_footer.setVisibility(View.GONE);
        mListView.addFooterView(listview_footer);
    }

    @Override
    protected void initData() {
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
        getData();
    }

    @Override
    protected void setListener() {
        back_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
//        mCommentSwipeRefresh.setOnRefreshListener(new TouchSwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                mCurrentPage = 1;
//                isDown = true;
//                getData();
//
//            }
//        });

        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                // 当不滚动时
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        //加载更多功能的代码
                        if (-1 == mCurrentPage) {
                            if(mData.size() > 0){
                                listview_footer.setVisibility(View.VISIBLE);
                            }
                            return;
                        }
                        mProgressBar_Modern.setVisibility(View.VISIBLE);
                        mLoadNoreInternalTime = System.currentTimeMillis() + 2000;
                        mCommentSwipeRefresh.setRefreshing(false);
                        isDown = false;
                        getData();
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });

    }

    public void closeLoadMoreView(long currenttime) {
        if (currenttime < mLoadNoreInternalTime) {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    mProgressBar_Modern.setVisibility(View.GONE);
                }
            }, 1000);
        }else {
            mProgressBar_Modern.setVisibility(View.GONE);
        }
    }

    /**
     * 从网络获取数据
     */
    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("pageSize", "20");
        map.put("pageNo", mCurrentPage + "");
        // map.put("sd", "84242008");
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                closeLoadMoreView(System.currentTimeMillis());
                BaseDataBean<BaseListDataBean<Consume>> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<BaseListDataBean<Consume>>>() {}.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);

                    if (result != null) {
                        if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {
                            showShortToast(result.getError_msg());
                        }else {
                            if (result.getData().getData().size() == 0) {
                                no_consume.setVisibility(View.VISIBLE);
                                //ToastMgr.showShortToast( "当前没有消费记录");
                            }else {
                                no_consume.setVisibility(View.GONE);
                            }
                            if (isDown) {
                                // TODO 在这里判断是否允许回复
                                // 下拉刷新
                                //  ptrLv.setPullToRefreshEnabled(true);
                                mData = result.getData().getData();
                                mAdapter.setDatas(mData);
                            }else {
                                // 上拉加载,数据追加
                                mAdapter.addDatas(result.getData().getData());
                            }
                            mCurrentPage = mCurrentPage + 1;
                            total = Integer.parseInt(PublicUtil.isNum(result.getData().getTotal()));
                            if (mData.size() >= total) {
                                mCurrentPage = -1;
                            }
                        }
                    }else {
                        showShortToast(R.string.laikan_data_load_failed);
                    }
                }catch (JsonSyntaxException e) {
                    // 数据解析失败
                    showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                    return;
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                closeLoadMoreView(System.currentTimeMillis());
                mCommentSwipeRefresh.setRefreshing(false);
                mCommentSwipeRefresh.setLoading(false);
                showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。31");
            }

            @Override
            public void onFinish() {
                closeLoadMoreView(System.currentTimeMillis());
                mCommentSwipeRefresh.setRefreshing(false);
                mCommentSwipeRefresh.setLoading(false);

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_personal_consume);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_personal_consume, map, null, null, requestListener);
    }

}
